<template>
  <CDialog
    title="关联盘查数据"
    descText="请先选择完所有筛选项"
    size="default"
    v-model:visible="dialogVisible"
    :loading="loading"
    :footer="false"
  >
    <div class="model-select-dialog-container">
      <div class="g-flex-start-center g-mb12">
        <CSelect
          remote
          size="default"
          v-model="searchForm.org"
          placeholder="组织名称"
          filterable
          style="width: 192px"
          @change="handleChange"
        >
          <template #suffix>
            <CIcon class="header-select--remote-icon" type="c-xian-sousuo"></CIcon>
          </template>
          <el-option
            v-for="item in companyList"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          ></el-option>
        </CSelect>
        <el-date-picker
          size="default"
          type="year"
          placeholder="年份"
          v-model="searchForm.inventoryYear"
          @change="handleChange"
          value-format="YYYY"
          :clearable="false"
          style="width: 100px; margin: 0 8px"
        ></el-date-picker>
        <CSelect
          size="default"
          v-model="searchForm.fuels"
          placeholder="请选择能源/燃料"
          :disabled="!searchForm.org || !searchForm.inventoryYear"
          filterable
          style="width: 158px"
          @change="handleSearch"
        >
          <template #suffix>
            <CIcon class="header-select--remote-icon" type="c-xian-sousuo"></CIcon>
          </template>
          <el-option
            v-for="item in fuelsList"
            :key="item.materialNo"
            :value="item.inventoryFacilities"
            :label="item.materialName"
          ></el-option>
        </CSelect>
        <CSelect
          class="g-ml8"
          size="default"
          v-model="searchForm.facilityLocation"
          placeholder="请选择设备位置"
          filterable
          :disabled="!searchForm.org || !searchForm.inventoryYear"
          style="width: 150px"
          @change="handleSearch"
        >
          <el-option
            v-for="item in facilityLocationOptions"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          ></el-option>
        </CSelect>
        <div id="model-select-header-right"></div>
      </div>
      <CTable
        ref="modelSelectTableRef"
        v-bind="tableOptions"
        @checkbox-change="handleCheck"
        :data-source="tableList"
        useDataSource
      >
        <vxe-column type="checkbox" width="50" fixed="left"></vxe-column>
        <vxe-column title="数据周期" field="fillPeriod"> </vxe-column>
        <vxe-column title="活动数据" align="right" field="activityData"> </vxe-column>
        <vxe-column title="单位" field="activityDataUnit"></vxe-column>
        <vxe-column width="100" title="产量(台)" align="right" field="yield"> </vxe-column>
      </CTable>
      <div class="footer">
        <span class="des"
          >总用量:{{ state.total }}{{ state.unit }}，产量:{{ state.yieldTotal }}，单位用量:{{
            state.dosage
          }}{{ state.unit }}</span
        >
        <div>
          <el-button size="default" @click="dialogVisible = false">取消</el-button>
          <el-button
            size="default"
            type="primary"
            @click="handleConfirm"
            :loading="loading"
            :disabled="!selectLength"
            >{{ `关联选中${selectLength}` }}</el-button
          >
        </div>
      </div>
    </div>
  </CDialog>
</template>

<script lang="ts" setup>
import { defineProps, withDefaults, defineEmits, computed, ref, reactive, watch } from 'vue';
import { CDialog } from '@/components/CDialog';
import { CTable, CTableProps } from '@/components/CTable';
import { CSelect } from '@/components/CSelect/index';
import { removeUndefinedParams } from '@/utils/index';
import { getCurrentOrganizationList } from '@/apis/common/common';
import {
  queryFillTaskDetailList,
  getMaterialList,
  getListFacilityLocation
} from '@/apis/pcf/myModel/modelDetail';
import { IFillTaskDetailListItem } from '@/apis/pcf/myModel/model/modelDetailModel';
import { uniq } from 'lodash';
import { useMessage } from '@/hooks/useMessage';

interface ModelSelectDialogProps {
  visible: boolean;
  processNo: string;
  modelNo: string;
  nodeNo: string;
}
const props = withDefaults(defineProps<ModelSelectDialogProps>(), {});
interface ModelSelectDialogEmits {
  (e: 'update:visible', visible: boolean): void;
  (e: 'select', row: any): void;
}
const selectLength = ref(0);
const emits = defineEmits<ModelSelectDialogEmits>();
const { createMessage } = useMessage();
const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emits('update:visible', val);
  }
});
watch(
  () => dialogVisible.value,
  visible => {
    if (!visible) {
      init();
    }
  }
);
const init = () => {
  searchForm.org = '';
  searchForm.inventoryYear = '';
  searchForm.fuels = '';
  searchForm.facilityLocation = '';
  fuelsList.value = [];
  facilityLocationOptions.value = [];
  tableList.value = [];
  state.total = 0;
  state.unit = '';
  state.yieldTotal = 0;
  state.dosage = 0;
  selectLength.value = 0;
};
const state = reactive({
  total: 0,
  unit: '',
  yieldTotal: 0,
  dosage: 0 as number | string,
  nodeNo: props.nodeNo
});
const loading = ref(false);
/**
 * 搜索
 */
const searchForm = reactive({
  org: '',
  inventoryYear: '',
  fuels: '',
  // 筛选范围
  facilityLocation: ''
});

/**
 * 筛选范围 option
 */
// eslint-disable-next-line no-undef
const facilityLocationOptions = ref<LabelValueOptions>([]);

/**
 * table ref
 */
const modelSelectTableRef = ref();
const tableList = ref<IFillTaskDetailListItem[]>([]);
/**
 * 搜索
 */

const companyList = ref([] as any[]);
const fuelsList = ref([] as any[]);

const loadCompany = () => {
  getCurrentOrganizationList().then(res => {
    companyList.value = res.map(item => {
      return {
        label: item.organizationName,
        value: item.organizationCode
      };
    });
  });
};
loadCompany();
const handleSearch = () => {
  // NOTE 所有筛选项均必填
  if (searchForm.fuels) {
    loadData();
  }
  state.total = 0;
  state.unit = '';
  state.yieldTotal = 0;
  state.dosage = 0;
  selectLength.value = 0;
};

const handleChange = () => {
  searchForm.fuels = '';
  searchForm.facilityLocation = '';
  if (searchForm.org && searchForm.inventoryYear) {
    getMaterialList(searchForm.org, searchForm.inventoryYear).then(res => {
      fuelsList.value = res;
    });

    getListFacilityLocation(searchForm.org, searchForm.inventoryYear).then(res => {
      facilityLocationOptions.value = [
        {
          label: '全厂',
          value: ''
        },
        ...res.map(item => {
          return {
            label: item,
            value: item
          };
        })
      ];
    });
  } else {
    fuelsList.value = [];
    facilityLocationOptions.value = [];
  }
  tableList.value = [];
};
// 表格数据获取
async function loadData() {
  const params = handleParams();
  let data = await queryFillTaskDetailList(params);
  tableList.value = data ?? [];
}

// 处理参数
const handleParams = () => {
  // 参数
  let params = {
    orgCode: searchForm.org,
    inventoryYear: searchForm.inventoryYear,
    inventoryFacilities: searchForm.fuels,
    // 筛选范围
    facilityLocation: searchForm.facilityLocation || ''
  };
  params = removeUndefinedParams(params);
  return params;
};
/**
 * 选择操作
 */
function handleConfirm() {
  if (state.yieldTotal <= 0) {
    createMessage.error('总产量为0，无法关联盘查数据');
    return;
  }
  emits('select', state);
  dialogVisible.value = false;
}
/**
 * 表格配置
 */
const tableOptions: CTableProps = {
  pagination: false,
  extraTableOption: {
    height: '380'
  }
};

function isAllSame(array: any[]) {
  return uniq(array).length === 1;
}

const handleCheck = (val: any) => {
  const records: any[] = val.getCheckboxRecords();
  selectLength.value = records.length;
  if (records && records.length) {
    let unitArr = records.map(item => item.activityDataUnit);
    let totalNum = records.reduce((prev, curr) => prev + curr.activityData, 0);
    state.unit = unitArr[0];
    state.total = totalNum;
    state.yieldTotal = records.reduce((prev, curr) => prev + curr.yield, 0);
    state.dosage = state.yieldTotal ? parseFloat((totalNum / state.yieldTotal).toFixed(9)) : '-';
    if (!isAllSame(unitArr)) {
      createMessage.warning('不同的单位的数据不能计算');
    }
  }
};
</script>

<style scoped lang="scss">
.model-select-dialog-container {
  padding-bottom: 60px;
  .footer {
    width: 100%;
    position: absolute;
    bottom: 0;
    height: 60px;
    padding: 13px 25px 20px;
    left: 0;
    display: flex;
    justify-content: space-between;
    background: #ffffff;
    align-items: center;
    .des {
      font-size: 14px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      color: #435970;
      line-height: 22px;
    }
  }
}
</style>
